package com.example.demo.controlller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User:xieChao
 * Date:2022/12/4 21:23
 */
@Slf4j
@Controller
@RequestMapping("/user")
@ResponseBody
public class UserController {
    //从配置文件中读取文件保存路径
    @Value("${img.path}")
    private String imgPath;
    @RequestMapping("/sayhi")
    @ResponseBody
    public String sayHi(){
        return "hello " +imgPath;
    }
    @RequestMapping("/upimg")
    @ResponseBody
    public boolean upImg(Integer id, @RequestPart("img") MultipartFile file){
        boolean result = false;
        try {
            //此种写法是把文件名写死了，下一个上传会覆盖前一个文件
            file.transferTo(new File("C:\\Users\\xie-xianzhi\\xc\\img.jpg"));
            result = true;
        } catch (IOException e) {
            log.error("上传失败：" + e.getMessage());
        }
        return  result;
    }


    //1.解决目录
    //2.图片名称（不能重复）(UUID)
    //3.获取原来上传图片格式
    @RequestMapping("/upimg1")
    @ResponseBody
    public boolean upImg1(Integer id, @RequestPart("img") MultipartFile file){
        boolean result = false;
        //得到图片名称
        String fileName = file.getOriginalFilename();
        //图片后缀
        fileName = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID().toString() + fileName;
        try {
            file.transferTo(new File(imgPath + fileName));
            result = true;
        } catch (IOException e) {
            log.error("上传失败：" + e.getMessage());
        }
        return  result;
    }


    /**
     * 存储session
     */
    @RequestMapping("/setsession")
    @ResponseBody
    public boolean setsession(HttpServletRequest request){
        boolean result = false;
        //1.得到HttpSession
        HttpSession session = request.getSession(true);
        //2.使用setAtt设置值
        session.setAttribute("userinfo","谢超");
        result = true;
        return result;
    }
    @RequestMapping("/getua")
    @ResponseBody
    public String getHead(HttpServletRequest request){
        return "header: " + request.getHeader("User-Agent");
    }

    /**
     * 获取session
     */
    @RequestMapping("/getsession")
    public String getsession(@SessionAttribute(value = "userinfo",
            required = false)String userinfo){
        return "会话："+userinfo;
    }
}
